<template>
  <div id="app">
<!--    <div id="app" v-loading.fullscreen.lock="fullscreenLoading">-->
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

<script>
import API from "@/api/apiBase";
import IndexMain from "@/components/index/IndexMain";
import menuList from "@/router/menuConfig";
import { mapActions } from 'vuex';
export default {
  name: "app",
  data() {
    return {
      // fullscreenLoading: false,
      loading: null,
     // ws: null,
    };
  },

  
  created() {
        this.$store.dispatch('initializeSocket');
        this.$bus.$on("websocket-message",(data)=>{
          this.sendMsgToWindows(data);
        })
    },
  mounted() {
    // if (this.$store.state.token) {
    //   this.getPermissionList();
    // }
    // this.init();
    // const token = this.$store.state.token;
    // if (!token) return;
    // if (!window.WebSocket) {
    //   Message.error("您的浏览器不支持WebSocket");
    //   return;
    // }
    // // 创建WebSocket连接
    // console.log("VUE_APP_WEBSOCKET_URL===", process.env.VUE_APP_WEBSOCKET_URL)
    // this.ws = new WebSocket(process.env.VUE_APP_WEBSOCKET_URL + "/checkorder/websocket/" + token + "/2");
    // // this.ws = new WebSocket("wss://checkorder.mejour.cn/checkorder/websocket/" + token + "/2");

    // // 监听WebSocket事件
    // this.ws.onopen = () => {
    //   console.log('WebSocket连接已建立');
    // };

    // this.ws.onmessage = (event) => {
    //   console.log('收到消息：', event.data);
    //   this.sendMsgToWindows(event.data)
    // };

    // this.ws.onclose = () => {
    //   console.log('WebSocket连接已关闭');
    // };
  },

  watch: {
    "$store.state.token"() {
      this.getPermissionList();
    }
  },
  methods: {
    ...mapActions(['handleChangeisRead']),
    getPermissionList() {
      const params = {
        token: this.$store.state.token
      };
      API.getPermissionList(params).then(res => {
        if (res.key === 1000) {
          res = res.result;
          const permissionList = res.list;
          const permissionNameList = [];
          let hasMedium = false;
          res.list.forEach(item => {
            const [itemName] = item.permission.split(":");
            permissionNameList.push(itemName);
            if(itemName == "medium"){
              hasMedium = true;
            }
          });
          if(hasMedium){
            permissionList.push({
              id: -10,
              isChoose: null,
              list: [
                // {
                //   buttonId: -2,
                //   buttonName: "首页新增",
                //   isChooseButton: null,
                //   permission: "homePage:add"
                // },
              ],
              permission: "mediumDate:view",
              powerName: "媒体日历"
            })
          }
          permissionList.push({
            id: -1,
            isChoose: null,
            list: [
              {
                buttonId: -2,
                buttonName: "首页新增",
                isChooseButton: null,
                permission: "homePage:add"
              },
              {
                buttonId: -3,
                buttonName: "首页修改",
                isChooseButton: null,
                permission: "homePage:edit"
              }
            ],
            permission: "homePage:view",
            powerName: "首页"
          })
          this.$ls.set("mujingpermissionNameList", permissionNameList);
          this.$store.commit("savePermissionNameList", permissionNameList);
          this.$ls.set("mujingpermissionList", permissionList);
          this.$store.commit("savePermissionList", permissionList);
          const route = {
            path: "/",
            name: "Index",
            component: IndexMain,
            redirect: "/device",
            children: []
          };
          if (permissionList && permissionList.length > 0) {
            menuList.forEach(menuItem => {
              // 全路由表
              if (menuItem.sub && menuItem.sub.length > 0) {
                // 如果有子路由
                let temporary = {
                  name: menuItem.name,
                  menuIcon: menuItem.menuIcon,
                  id: menuItem.id,
                  pathName: menuItem.pathName,
                  componentName: menuItem.componentName,
                  sub: []
                };
                menuItem.sub.some(subItem => {
                  const subName = subItem.id.replace(
                      subItem.id[0],
                      subItem.id[0].toLowerCase()
                  );
                  permissionList.some(firstItem => {
                    // 权限表
                    const [firstName] = firstItem.permission.split(":");
                    if (subName === firstName) {
                      // 如果第一层相等
                      temporary.sub.push({
                        name: subItem.name,
                        id: subItem.id,
                        pathName: subItem.pathName,
                        componentName: subItem.componentName
                      });
                      route.children.push({
                        // 添加实际路由
                        path: subItem.pathName,
                        name: subItem.id,
                        meta: {
                          tabName: subItem.name
                        },
                        component: () => subItem.componentName
                      });
                      if (subItem.child && subItem.child.length > 0) {
                        // 操作路由
                        subItem.child.forEach(subChildItem => {
                          if (firstItem.list){
                            if (firstItem.list.length === 0 && subChildItem.type === "all") {
                              route.children.push({
                                // 添加实际操作路由
                                path: subChildItem.pathName,
                                name: subChildItem.id,
                                meta: {
                                  tabName: subChildItem.name
                                },
                                component: () => subChildItem.componentName
                              });
                              subChildItem.used = true;
                            } else {
                              firstItem.list.some(listItem => {
                                const listType = listItem.permission.split(":")[1];
                                let arr = subChildItem.type.split(",");
                                if (arr.indexOf(listType) != -1 || subChildItem.type === "all" && !subChildItem.used) {
                                  route.children.push({
                                    // 添加实际操作路由
                                    path: subChildItem.pathName,
                                    name: subChildItem.id,
                                    meta: {
                                      tabName: subChildItem.name
                                    },
                                    component: () => subChildItem.componentName
                                  });
                                  subChildItem.used = true;
                                }
                              });
                            }
                          }
                        });
                      }
                    }
                  });
                });
                this.$store.state.menuList.push(temporary);
              } else {
                const menuName = menuItem.id.replace(
                    menuItem.id[0],
                    menuItem.id[0].toLowerCase()
                );
                permissionList.some(firstItem => {
                  // 权限表
                  const [firstName] = firstItem.permission.split(":");
                  if (menuName === firstName) {
                    // 如果第一层相等
                    this.$store.state.menuList.push({
                      // 添加显示用菜单
                      name: menuItem.name,
                      menuIcon: menuItem.menuIcon,
                      id: menuItem.id,
                      pathName: menuItem.pathName,
                      componentName: menuItem.componentName
                    });
                    route.children.push({
                      // 添加实际路由
                      path: menuItem.pathName,
                      name: menuItem.id,
                      meta: {
                        tabName: menuItem.name
                      },
                      component: () => menuItem.componentName
                    });
                    if (menuItem.child && menuItem.child.length > 0) {
                      // 操作路由
                      menuItem.child.forEach(menuChildItem => {
                        if (firstItem.list){
                          if (firstItem.list.length === 0 && menuChildItem.type === "all") {
                            route.children.push({
                              // 添加实际操作路由
                              path: menuChildItem.pathName,
                              name: menuChildItem.id,
                              meta: {
                                tabName: menuChildItem.name
                              },
                              component: () => menuChildItem.componentName
                            });
                            menuChildItem.used = true;
                          } else {
                            firstItem.list.some(listItem => {
                              const listType = listItem.permission.split(":")[1];
                                let arr = menuChildItem.type.split(",");
                              if (arr.indexOf(listType) != -1 || menuChildItem.type === "all" && !menuChildItem.used) {
                                route.children.push({
                                  // 添加实际操作路由
                                  path: menuChildItem.pathName,
                                  name: menuChildItem.id,
                                  meta: {
                                    tabName: menuChildItem.name
                                  },
                                  component: () => menuChildItem.componentName
                                });
                                menuChildItem.used = true;
                              }
                            });
                          }
                        }
                      });
                    }
                  }
                });
              }
            });
          }
          console.log(route);
          this.$router.addRoutes([route]);
          this.$router.push({
            path: "/homePage"
          });
        }
      });
    },
    init() {
      this.$bus.$on("show-loading", bol => {
        if (bol) {
          // if (this.loading) {
          //   this.$loading({
          //     lock: true,
          //     background: "transparent"
          //   });
          // } else {
            this.loading = this.$loading({
              lock: true,
              background: "transparent"
            });
          // }
        } else {
          if (this.loading) {
            this.loading.close();
          }
        }
      });
    },
    sendMsgToWindows(msg, title = "通知") {
      // 判断浏览器是否支持唤醒
      console.log("---------", window.Notification)
      if (window.Notification) {
        console.log("-------1222--------")
        let popNotice = () => {
          console.log("Notification-----")
          if (Notification.permission !== "granted") return;
          const notification = new Notification(title, {
            body: msg,
          });
          // 点击通知的回调函数
          notification.onclick = function () {
            // window.open('https://baidu.com')
            // router.push("/banner");
            notification.close();
          };
          this.$notify({
            title: title,
            message: msg,
            duration: 4500
          });
        };
        console.log("----授权判断-------", Notification.permission)
        /* 授权过通知 */
        if (Notification.permission === "granted") {
          popNotice();
        } else if (Notification.permission !== "denied") {
          /* 未授权且未拒绝，询问授权 */
          Notification.requestPermission().then(permission => {
            // 检查用户是否授予权限
            if (permission === "granted") {
              popNotice();
            }
          });
        }
      } else {
        // 浏览器不支持通知时，仅显示应用内通知
        this.$notify({
          title: title,
          message: msg,
          duration: 4500
        });
        console.log("当前浏览器不支持桌面通知");
      }
    },
    confirmAction() {
      // 使用简单的JavaScript确认对话框作为示例
      if (confirm("您是否确认该操作？")) {
        console.log("用户已确认");
        // 在这里执行确认后的逻辑
      } else {
        console.log("用户取消了操作");
      }
    },
  }
};
</script>

<style lang="sass" scoped>
</style>
